<?php

namespace App\Http\Services;

use App\Http\Model\Device as DeviceModel;
use App\Http\Model\Hint;
use App\Http\Model\User as UserModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Services\PlatformReportServices;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

class DeviceServices extends CommonServices
{
    protected $deviceModel;
    protected $userModel;
    protected $userServices;
    protected $platformReportServices;

    public function __construct(DeviceModel $deviceModel, UserModel $userModel)
    {
        parent::__construct();

        $this->deviceModel = $deviceModel;
        $this->userModel = $userModel;
        $this->userServices = new UserServices();
        $this->platformReportServices = new PlatformReportServices();
    }

    protected function checkField(&$params = [])
    {
        $flag = true;

        do {
            $checkField = ['guid', 'idfa', 'version_no', 'os_name', 'device', 'channel_id', 'platform','imei','oaid','adid','conv_ext'];
            if (empty($params)) {
                $flag = false;
                break;
            }

            $inputParams = [];
            foreach ($checkField as $field) {
                if (array_key_exists($field, $params)) {
                    $inputParams[$field] = $params[$field];
                }
            }

            $params = $inputParams;
        } while (false);

        return $flag;
    }

    public function savePlatform($params = [])
    {
        $code = Hint::SUCCESS;
        $data = [];

        do {
            try {
                $params = array_merge($params, $this->parse_app_UA());

                // 校验字段
                $this->checkField($params);
                if (empty($params)) {
                    $code = Hint::PARAM_ERROR;
                    $data['error_mgs'] = '参数不能为空';
                    break;
                }

                // 如果渠道号Id或者guid为空就不再做后续操作
                if (empty($params['platform']) || empty($params['guid'])) {
                    break;
                }

                $params['idfa'] = strtolower($params['idfa'] ?? '');

                // 检测数据是否存在
                $checkParams = [
                    'guid' => $params['guid'] ?? '',
                ];
                $checkDeviceData = $this->deviceModel->get($checkParams, true);
                if (!empty($checkDeviceData) && !empty($checkDeviceData['platform'])) {
                    $data['notice_msg'] = '设备信息已存在';
                    break;
                }
                if (!empty($checkDeviceData) && empty($checkDeviceData['platform'])) {
                    $this->deviceModel->updateDevice($checkParams, $params['platform']);
                } else {
                    $this->deviceModel->save($params);
                }

            } catch (\Exception $e) {
                $code = Hint::NOT_ALLOWED;
                $data['error_mgs'] = $e->getMessage();
                break;
            }
        } while (false);

        $result = compact('code', 'data');

        return $result;
    }


    public function repeat($params = [])
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                // 校验字段
                $this->checkField($params);
                if (empty($params) or empty($params['idfa'])) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code);
                    break;
                }

                $checkData = $this->deviceModel->get($params, true);
                if (!empty($checkData)) {
                    $code = Hint::ERR_DATA_EXIST;
                    $msg = Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'msg');
    }

    //广告归因，上报激活
    public function save($params = [])
    {
        $code = Hint::SUCCESS;
        $data = [];

        do {
            try {
                $clientIp = client_ip();
                $params = array_merge($params, $this->parse_app_UA());
                $httpWebviewUa = $_SERVER['HTTP_WEBVIEW_UA'] ?? '';//ua

                // 校验字段
                $this->checkField($params);
                if (empty($params)) {
                    $code = Hint::PARAM_ERROR;
                    $data['error_mgs'] = '参数不能为空';
                    break;
                }

                $params['ua'] = $httpWebviewUa;
                $params['client_ip'] = $clientIp;

                // 检测数据是否存在
                $checkParams = [
                    'guid' => $params['guid'] ?? '',
                ];
                $checkDeviceData = $this->deviceModel->get($checkParams, true);
                if (!empty($checkDeviceData)) {
                    //快手次日留存
                    if($params['channel_id'] == '900001'){
                        $oaid = md5($params['oaid']);
                        $logId = $this->deviceModel->getChannelLogByGuid($params['guid']);
                        write_log('device', '设备信息', [$logId]);
                        
                        if(empty($logId))
                        {
                            break;
                        }
                        //查看是否是昨天激活的APP不是的话不上报
                        $chanle_time = $logId['created_at'];
                        $isYestorday = Carbon::parse($chanle_time)->isYesterday();
                        if($isYestorday){
                            //避免重复上报次日留存
                            $todayReport = Redis::get('DEVICE:REOPRT:KUAISHOU:'.$oaid);
                            if(empty($todayReport)){
                                $this->platformReportServices->reportActivation($logId['id'],1);
                                $endOfday = Carbon::today()->endOfDay();
                                $nowtime = Carbon::now()->toDateTimeString();
                                $diffSecond = Carbon::parse($nowtime)->diffInSeconds($endOfday);
                                //设置当天缓存
                                Redis::set('DEVICE:REOPRT:KUAISHOU:'.$oaid,1);
                                Redis::EXPIRE('DEVICE:REOPRT:KUAISHOU:'.$oaid,$diffSecond);
                            }
                        }
                        write_log('device', '非昨日激活的不上报', [$logId]);
                        
                    }
                    $data['notice_msg'] = '设备信息已存在，无需添加';
                    break;
                }

                $params['platform'] = '';// 默认平台
                $params['cid'] = '';
                $params['aid'] = '';
                $params['advertiser_id'] = '';
                $params['idfa'] = $params['idfa'] ?? '';
                $params['oaid'] = $params['oaid'] ?? '';
                $this->deviceModel->save($params);
                //渠道广告点击记录
                $logId = 0;
                if(!empty($params['guid']) && !empty($params['oaid'])) {
                    $oaid = $params['oaid'];
                    if($params['channel_id'] == '900001'){
                        $oaid = md5($params['oaid']);
                    }
                    $logId = $this->deviceModel->checkChannelPlatform($params['guid'], $params['channel_id'], 'oaid', $oaid);
                }

                //广告归因，上报激活
                $this->platformReportServices->reportActivation($logId);

            } catch (\Exception $e) {
                $code = Hint::NOT_ALLOWED;
                $data['error_mgs'] = $e->getMessage();
                break;
            }
        } while (false);

        $result = compact('code', 'data');

        return $result;
    }

    //广告点击回调
    public function clackCallback($params = [])
    {
        $code = Hint::ERROR;
        $msg = '';

        do {
            try {
                $platform = empty($params['platform']) ? '' : $params['platform'];
                if(empty($platform)) {
                    $msg = '无 platform 参数';
                    break;
                }
                //vivo聚力
                if($params['platform'] == 'vivo-juli') {
                    foreach($params as $param) {

                        if(is_array($param) && !empty($param['oaid'])) {
                            $log = [];
                            $log['oaid'] = $param['oaid'];
                            $log['platform'] = $platform;//来自平台
                            $log['rid'] = empty($param['requestId']) ? '' : $param['requestId'];//请求 ID
                            $log['request_info'] = $param;//数据记录json
                            //缓存记录
                            $this->deviceModel->setChannelPlatformRequest('oaid', $param['oaid'], $log);
                        }
                    }
                }
                //华为亨利
                if($params['platform'] == 'huawei-hengli') {
                    if(!empty($params['oaid'])) {
                        $log = [];
                        $log['oaid'] = $param['oaid'];
                        $log['platform'] = $platform;//来自平台
                        $log['request_info'] = $param;//数据记录json
                        //缓存记录
                        $this->deviceModel->setChannelPlatformRequest('oaid', $param['oaid'], $log);
                    }
                }
                //快手-韵洪
                if($params['platform'] == 'kuaishou-yunhong'){
                    if(!empty($params['oaid'])) {
                        $log = [];
                        $log['oaid'] = $params['oaid'];
                        $log['platform'] = $platform;//来自平台
                        $log['rid'] = empty($params['requestId']) ? '' : $params['requestId'];//请求 ID
                        $log['request_info'] = $params;//数据记录json
                        write_log('device','收到参数',$log);
                        //缓存记录
                        $this->deviceModel->setChannelPlatformRequest('oaid', $params['oaid'], $log);
                    }
                }
                $code = Hint::SUCCESS;
            } catch (\Exception $e) {
                $code = Hint::ERROR;
                break;
            }
        } while (false);

        return ['code'=>$code, 'msg'=>$msg];
    }

}
